package com.tianyu.common;

import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.TreeMap;

public class RSAEncryptionTool {

    public static final String publicKeyPem = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoR+VMSZU0" +
            "7yPueJJekiEAotZd/HwKlCP6/su4uqgLRg0+plV6tYpJ9Q70jEApyyTzbgoE9ByURLcf5P+wxLC+QNtH4ZUun" +
            "n/70DfQ6AtlyjK8qTDoi8tBBTpeNFfO9O/bOGYaquMIZHqm+w4wH9nGRyuc3M8CILKSsEAwyuySEHmFPqct1+" +
            "ikdly4n5U8kRJMwazFOJwdu4uVS7Lukvly11Y2ToQACoG8laKN4hwMX3iCPxalvHUihmPHLPVR+IO6MJuBnm3" +
            "FodsskwGAQWiJ4QBvMvkTc37ultLQxRRSZoBCAhng20ob01GpRbrLxmeJt91/gW8cFUwR2efyK5xRwIDAQAB";

    public static final String privateKeyPem = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQChH" +
            "5UxJlTTvI+54kl6SIQCi1l38fAqUI/r+y7i6qAtGDT6mVXq1ikn1DvSMQCnLJPNuCgT0HJREtx/k/7DEsL5A2" +
            "0fhlS6ef/vQN9DoC2XKMrypMOiLy0EFOl40V87079s4Zhqq4whkeqb7DjAf2cZHK5zczwIgspKwQDDK7JIQeY" +
            "U+py3X6KR2XLiflTyREkzBrMU4nB27i5VLsu6S+XLXVjZOhAAKgbyVoo3iHAxfeII/FqW8dSKGY8cs9VH4g7o" +
            "wm4GebcWh2yyTAYBBaInhAG8y+RNzfu6W0tDFFFJmgEICGeDbShvTUalFusvGZ4m33X+BbxwVTBHZ5/IrnFHA" +
            "gMBAAECggEABaagamVgQz7RQaE0l4PUkWxGuoSzOiCyM4IPPmkhLgOz0/gtwbs6HUn9wRzz22keU/A6A5vjbo" +
            "F9V0IfBMNzMB2VJa5l6VZfCgqZ6frDrpIBMCpkLBuAdiyvlYuuTeBazdxJprAWjZTbCBXsVaACQyi025q2h8v" +
            "igWWse6vcKFmNEwE9kmBpWUiOl0CiNMwHUcrOxWBr1k3QAKSmzWATvrpPj60DO3/phk+RsLIUC8mjUQ1zV9Q8" +
            "yOzORrZ/+P04ti4K22AKa8x5qE+lVN8Z4Neltcbsnj3XF0Jqop1kLl+vEKsrw3b5n2IthrgH9OXu1Tu0LoNUq" +
            "fJMXHaqGQF/sQKBgQDPRRnqTmf6s0Et/qE74ll7RWIS07cqU+BGKdW6Byzib7MsXOCw6906dy4bbDheVR959z" +
            "WUbcLEYTO1nw0rHvoGUoc0eCwyqnVrBYcXJtX0cAAiOeVMBv2Wep9K0IdEwy02Bqbfvq7lBNL3OAB0OJ3ClNo" +
            "RyVi75Rpu5FQRtDhYlwKBgQDHARJASpA3lG2gL0vsL1rkckdle5CabJom72jySdPgPYfy58OUXy9WOsWHqE98" +
            "aGejoolqvrLPNXktzRZ3bcV7/ABp5xTnnwlvdfAho2VyIu91GVspmuiG/C70XAzD7vehlu8ZGbKA2yhnDK9BH" +
            "rQFin+/n0MeXK2bRFVfOhiS0QKBgQCW4Hw+3Rg/nCDENGh1yQzN+PGtNsRMYYYOTQGxSuvXYOwSTQGah/cgSg" +
            "UcHSjjMh+ZjuRHyaZPgVo8ySyyyPfDhmu5PAkgUIjsgLeXmMOCDc1rHK3XK/eIhHZT5XuyCElu3GS41ntFZr+" +
            "TCgb6kwPz0pry+5hGHj2hnz+7K28gvQKBgEolSgmOPoGW2emO9bjARBtNwPA8w7nlsOHE3dM4UqsAAgEs/R/w" +
            "/xAfwa0ztrnhpIvBaXXOK40snUPFYBOLYMM7N2Q95voNtVREGv5NhOSrw5BbrC2qO+zfVRdSnKb8CGO6esddX" +
            "bbI8RrEDSA0MlrGKabZzgYn/b8WDMD4QmOhAoGAVyjRaA/tqEj8xv2qANy7dbGXyGONHpdmTDucpRowornlcF" +
            "KIG36r+KDe/TPlaloQF+TCRtTwxh9Ksfy/sMsFmyGB1/E6pAwJW3YaLNyXEqNZ9LE+u+BMEb6aWL2+WaLdcrp" +
            "RodjeKt6/Zd1TU7xcli3PRItP58QFfnllhjO2Mak=";
    public static void main(String[] args) throws Exception {
//
//        final long l = System.currentTimeMillis();
//        final JSONObject data = RSAEncryptionTool.rsaStringBuild();
//        final long l2 = System.currentTimeMillis();
//
//        System.out.println(l2-l);
//        System.out.println(data);

        System.out.println("publicKeyPem: "+publicKeyPem);
        System.out.println("privateKeyPem: "+privateKeyPem);

//        // 2. 加密字符串
//        final JSONObject jsonObject = JSONObject.of();
        TreeMap<String, Object> jsonObject = new TreeMap<>();
        jsonObject.put(".Auth-Token","123");
        jsonObject.put(".method","FLIGHT_TASK");
        jsonObject.put(".tid","4b7dc515-f26b-4af0-a1fe-d23881b0a460");
        jsonObject.put(".timestamp","1720971392815");
        jsonObject.put("missionId","5392");
        jsonObject.put("sn","M26220230415013");

        String originalString = JSONObject.from(jsonObject).toString();
        final String base64String = Base64.getEncoder().encodeToString(originalString.getBytes());
        final String md5Hash = getMD5Hash(base64String);
        System.out.println(md5Hash);
        byte[] encryptedBytes = encrypt("123", publicKeyPem);
        String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted String: " + encryptedString);

        // 3. 解密字符串（可选）
        byte[] decryptedBytes = decrypt(encryptedBytes, privateKeyPem);
        String decryptedString = new String(decryptedBytes);
        System.out.println("Decrypted String: " + decryptedString);
    }


    // 1. 生成RSA密钥对
    private static final KeyPairGenerator keyPairGenerator;

    static {
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048); // 可以指定密钥长度，如2048位
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    public static JSONObject rsaStringBuild(){
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        // 获取公钥并转换为Base64字符串
        byte[] publicKeyBytes = publicKey.getEncoded();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKeyBytes);
        // 获取私钥并转换为Base64字符串
        byte[] privateKeyBytes = privateKey.getEncoded();
        String privateKeyString = Base64.getEncoder().encodeToString(privateKeyBytes);
        return JSONObject.of("rsaPublic", publicKeyString,"rsaPrivate", privateKeyString);
    }

    public static String getMD5Hash(String input) {
        try {
            // 获取MD5 MessageDigest实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 更新要加密的数据
            md.update(input.getBytes());

            // 完成加密操作
            byte[] digest = md.digest();

            // 将加密结果转换为16进制字符串
            BigInteger number = new BigInteger(1, digest);
            String hashtext = number.toString(16);

            // 确保哈希值始终为32个字符
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }

            return hashtext;

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }



    public static byte[] encrypt(String str, String publicKeyPEM) throws Exception {
        // 将私钥从Base64编码转换为字节数组
        byte[] encodedPublicKey = Base64.getDecoder().decode(publicKeyPEM);
        // 创建一个PKCS8EncodedKeySpec对象，这是私钥的规范
        X509EncodedKeySpec keySpecPKCS8 = new X509EncodedKeySpec(encodedPublicKey);
        // 创建一个KeyFactory对象来生成私钥
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(keySpecPKCS8);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
    }

    @SneakyThrows
    public static byte[] decrypt(byte[] encryptedBytes, String privateKeyPEM) {
        // 将私钥从Base64编码转换为字节数组
        byte[] encodedPrivateKey = Base64.getDecoder().decode(privateKeyPEM);
        // 创建一个PKCS8EncodedKeySpec对象，这是私钥的规范
        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(encodedPrivateKey);
        // 创建一个KeyFactory对象来生成私钥
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedBytes);
    }
}